<template>
  <div 
    class="user-avatar" 
    :class="[size, { clickable: clickable }]"
    @click="handleClick"
  >
    <img 
      :src="avatarUrl || defaultAvatar" 
      :alt="nickname || '用户头像'"
      class="avatar-image"
      @error="handleImageError"
      @load="onImageLoad"
    />
    
    <!-- 在线状态指示器 -->
    <div 
      v-if="showOnlineStatus && isOnline"
      class="online-indicator"
    ></div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="avatar-loading">
      <div class="loading-spinner"></div>
    </div>
  </div>
</template>

<script>
import { ref, computed, watch, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'

export default {
  name: 'UserAvatar',
  props: {
    // 用户ID
    userId: {
      type: [String, Number],
      default: null
    },
    // 头像URL（优先级高于userId）
    avatarUrl: {
      type: String,
      default: ''
    },
    // 用户昵称
    nickname: {
      type: String,
      default: ''
    },
    // 头像尺寸
    size: {
      type: String,
      default: 'medium', // mini, small, medium, large, extra-large
      validator: (value) => ['mini', 'small', 'medium', 'large', 'extra-large'].includes(value)
    },
    // 是否可点击
    clickable: {
      type: Boolean,
      default: false
    },
    // 是否显示在线状态
    showOnlineStatus: {
      type: Boolean,
      default: false
    },
    // 是否在线
    isOnline: {
      type: Boolean,
      default: false
    },
    // 是否懒加载
    lazy: {
      type: Boolean,
      default: false
    }
  },
  emits: ['click', 'load-error'],
  setup(props, { emit }) {
    const userStore = useUserStore()
    
    // 响应式数据
    const loading = ref(false)
    const loadError = ref(false)
    
    // 默认头像
    const defaultAvatar = '/images/default-avatar.png'
    
    // 计算属性
    const finalAvatarUrl = computed(() => {
      if (props.avatarUrl) {
        return props.avatarUrl
      }
      
      if (props.userId) {
        // 从用户store中获取头像
        const user = userStore.getUserById(props.userId)
        return user?.avatar || defaultAvatar
      }
      
      return defaultAvatar
    })
    
    // 处理头像点击
    const handleClick = () => {
      if (props.clickable) {
        emit('click', {
          userId: props.userId,
          avatarUrl: finalAvatarUrl.value,
          nickname: props.nickname
        })
      }
    }
    
    // 处理图片加载错误
    const handleImageError = (event) => {
      loadError.value = true
      event.target.src = defaultAvatar
      emit('load-error', {
        userId: props.userId,
        originalUrl: finalAvatarUrl.value
      })
    }
    
    // 处理图片加载完成
    const onImageLoad = () => {
      loading.value = false
      loadError.value = false
    }
    
    // 获取用户头像信息
    const loadUserAvatar = async () => {
      if (!props.userId || props.avatarUrl) return
      
      loading.value = true
      try {
        await userStore.loadUserInfo(props.userId)
      } catch (error) {
        console.error('加载用户头像失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    // 监听userId变化
    watch(() => props.userId, (newUserId) => {
      if (newUserId && !props.avatarUrl) {
        loadUserAvatar()
      }
    }, { immediate: true })
    
    // 组件挂载时加载头像
    onMounted(() => {
      if (props.userId && !props.avatarUrl && !props.lazy) {
        loadUserAvatar()
      }
    })
    
    return {
      loading,
      defaultAvatar,
      finalAvatarUrl,
      handleClick,
      handleImageError,
      onImageLoad
    }
  }
}
</script>

<style scoped>
.user-avatar {
  position: relative;
  display: inline-block;
  border-radius: 50%;
  overflow: hidden;
  background: #f5f5f5;
  flex-shrink: 0;
}

.user-avatar.clickable {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.user-avatar.clickable:hover {
  transform: scale(1.05);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

/* 在线状态指示器 */
.online-indicator {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 25%;
  height: 25%;
  background: #4caf50;
  border: 2px solid white;
  border-radius: 50%;
  min-width: 8px;
  min-height: 8px;
}

/* 加载状态 */
.avatar-loading {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
}

.loading-spinner {
  width: 50%;
  height: 50%;
  border: 2px solid #e0e0e0;
  border-top: 2px solid #1976d2;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 不同尺寸 */
.user-avatar.mini {
  width: 24px;
  height: 24px;
}

.user-avatar.small {
  width: 32px;
  height: 32px;
}

.user-avatar.medium {
  width: 48px;
  height: 48px;
}

.user-avatar.large {
  width: 64px;
  height: 64px;
}

.user-avatar.extra-large {
  width: 96px;
  height: 96px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .user-avatar.large {
    width: 56px;
    height: 56px;
  }
  
  .user-avatar.extra-large {
    width: 80px;
    height: 80px;
  }
}
</style> 